#download_media.py
import yt_dlp
import logging

# 下载单个视频
def download_single_video(url):
    ydl_opts = {
        'format': 'bestvideo+bestaudio/best',
        'outtmpl': '%(title)s.%(ext)s',
        'merge_output_format': 'mp4',
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# 下载单个音频
def download_single_audio(url):
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': '%(title)s.%(ext)s',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# 下载播放列表视频
def download_playlist_videos(url):
    ydl_opts = {
        'yesplaylist': True,
        'format': 'bestvideo+bestaudio/best',
        'outtmpl': '%(title)s.%(ext)s',
        'merge_output_format': 'mp4',
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# 下载播放列表音频
def download_playlist_audios(url):
    ydl_opts = {
        'yesplaylist': True,
        'format': 'bestaudio/best',
        'outtmpl': '%(title)s.%(ext)s',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
# 示例URL
av_url = 'https://www.bilibili.com/video/BV1xV411C7sw'

av_list_url = "https://www.bilibili.com/video/BV1xN411T7AL"


#https://www.bilibili.com/video/BV19M411e7rc


# 调用函数示例
# download_single_video(av_url)
# download_single_audio(av_url)
# download_playlist_videos(av_list_url)
# download_playlist_audios(av_list_url)


# 示例用法
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    download_playlist_audios(av_list_url)